import React, { useState } from 'react';
import styles from './index.less';
import { Alert, Button, Spin } from 'antd';
import Empty from '@/tool/components/PageEmpty';
import { connect } from 'umi';
import { isEmpty } from 'lodash';
import { getPageQuery } from '@/utils/utils';
// components
import { PageLoading, TRAlert, TRDefault, TRMessage } from '@/components';
import { FundProjectionScreenOutlined } from '@/utils/antdIcons';
import {
  AddModal,
  ChartBase,
  ChartZoom,
  ModalDataSource,
  ModalDetail,
  TableBase,
  Tool,
} from './components';
// api
import { mqttCentre } from '@/utils/mqttCentre.js';
import { getCounterPartyList, initFetch, MQTT_ENUM } from './services';
// hooks
import useDataHandle from './hooks/useDataHandle';
import usePower from './hooks/usePower';
import useResize from './hooks/useResize';
import { HttpCode } from '@/utils/contacts';
import moment from 'moment';
import { useExport } from './hooks/useExport';

export default connect(({ global }) => ({
  buttonPermissions: global.configure.buttonPermissions,
  menuCode: global.configure.menuCode,
}))(PositionManagement);

function PositionManagement({ menuCode, buttonPermissions }) {
  // 行编辑打开弹窗
  const handleEdit = async (r, counterPartyList) => {
    const today = moment().add(1, 'days').format('YYYY-MM-DD');
    const hasDate = Date.parse(today) > Date.parse(r.startDate);
    let obj = { index: 1 };
    if (hasDate) {
      obj = await TRAlert.show('所选时间范围内存在已执行日期合约');
    }
    // 编辑
    if (obj.index === 1) {
      await AddModal.show({
        pageQuery,
        counterPartyList,
        menuCode,
        type: 'edit',
        contractData: {
          contractName: r?.contractName || '',
          counterpartyId: r?.counterpartyId || null,
          contractId: r?.contractId || '',
        },
      });
    }
  };

  // 判断是否含url参数
  const pageQuery = getPageQuery();
  const pageType = isEmpty(pageQuery) ? 'main' : 'child';
  // 请求数据
  const [dataLoading, setDataLoading] = React.useState(false);
  const [form, setForm] = React.useState(pageType === 'main' ? null : pageQuery);
  const formRef = React.useRef(form);
  const [result, setResult] = React.useState(null);
  // 数据权限
  const { error, loading, powerData, stationMap } = usePower(menuCode, pageType);
  // 对手方列表
  const [counterPartyList, setCounterPartyList] = useState([]);
  // 数据处理
  const { charts, columns, tableData, total } = useDataHandle({
    buttonPermissions,
    pageType,
    form,
    result,
    handleEdit,
    counterPartyList,
  });
  // 计算列
  const wrapRef = React.useRef(null);
  const [startIndex, setStartIndex] = React.useState(0); // 起始列
  const [hoverColIndex, setHoverColIndex] = React.useState(-1); // 高亮列
  const { columnWidth, pageWidth, pageSize } = useResize(wrapRef, {
    total,
    minWidth: 35, // 设置最小列宽(大图、表格)
  });

  React.useEffect(() => {
    if (pageType === 'child') {
      // 根据省份id获取对手方
      fetchGetCounterPartyList();
    }
  }, [pageType]);

  const fetchGetCounterPartyList = async () => {
    const res = await getCounterPartyList(pageQuery.p);
    if (res.statusCode === HttpCode.SUCCESS) {
      let arr = res?.results || [];
      arr = arr.filter((i) => i.counterpartyType === 'system');
      setCounterPartyList(arr);
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
  };

  /** lifetimes */
  React.useEffect(() => {
    // 暂时注销链接
    // mqttCentre.connect('mosquitto', 'Mosquitto.com', 'wss://transaction.gw-ams.com:8083');
    Object.entries(MQTT_ENUM).map(([key, topic]) => {
      mqttCentre.subscribe(key, topic, () => {
        hanldeSubmit(formRef.current, false);
      });
    });
    // return () => {
    //   mqttCentre.end();
    // };
  }, []);

  /** methods */
  const onAction = (type, values) => {
    if (type === 'submit') {
      setForm({ ...values });
      return hanldeSubmit(values, true);
    } else if (type === 'add') {
      // 新增
      AddModal.show({ pageQuery, counterPartyList, menuCode });
    }
    if (type === 'export') return handleExport();
  };

  const hanldeSubmit = async (values, showLoading) => {
    if (dataLoading) return;
    formRef.current = values;
    // 查询
    !!showLoading && setDataLoading(true);
    const _stationMap =
      pageType === 'main' ? stationMap : { [values.stationId]: values.stationName };
    const result = await initFetch(values, _stationMap, pageType);
    result.sort((a, b) => a.stationName.localeCompare(b.stationName));
    !!showLoading && setDataLoading(false);
    setResult(result);
    // capacityMqtt(res.data, res.originData);
  };

  const handleExport = () => {
    if (!result || !columns?.length) return TRMessage.warning('请添加查询条件');
    // 导出
    if (pageType === 'main') {
      const canExport = buttonPermissions.some((x) => x.menuCode === 'positionManagementExport');
      if (!canExport) return TRMessage.info('请联系管理员获取相关权限');
    }
    useExport(tableData, { ...form, columns });
  };

  const handleTopBtn = (e) => {
    e.stopPropagation();
    if (pageType === 'main') {
      // 预测数据源管理
      ModalDataSource.show({ buttonPermissions, stationMap, form });
    }
    if (pageType === 'child') {
      // 数据源管理
      ModalDetail.show({ pageQuery });
      // onOpenOrClose();
    }
  };

  /** render */
  const _renderMain = () => {
    if (!result || !columns?.length)
      return (
        <div className={styles.my_empty}>
          <Empty />
          <Alert
            className={styles.my_empty__alert}
            message={'请添加查询条件'}
            type="warning"
            showIcon
          />
        </div>
      );
    return (
      <>
        <ChartZoom
          option={charts?.zoom}
          mark={charts?.mark}
          startIndex={startIndex}
          onChangeStartIndex={setStartIndex}
          hoverColIndex={hoverColIndex}
          total={total}
          pageSize={pageSize}
          pageWidth={pageWidth}
        />
        <div className={styles.chart_base}>
          <ChartBase
            option={charts?.base}
            startIndex={startIndex}
            pageSize={pageSize}
            hoverColIndex={hoverColIndex}
            onChangeHoverColIndex={setHoverColIndex}
          />
        </div>
        <div className={styles.tableWrap}>
          <TableBase
            columns={columns}
            dataSource={tableData}
            columnWidth={columnWidth}
            startIndex={startIndex}
            hoverColIndex={hoverColIndex}
            onChangeHoverColIndex={setHoverColIndex}
          />
          <div className={styles.topBtn}>
            <Button
              type="link"
              style={{ padding: 0 }}
              onClick={handleTopBtn}
              icon={<FundProjectionScreenOutlined />}
            >
              {pageType === 'main' ? '预测数据源管理' : '数据源管理'}
            </Button>
          </div>
        </div>
      </>
    );
  };

  const _render = () => {
    if (pageType === 'main') {
      if (loading) return <PageLoading />;
      if (!!error) return <TRDefault type="error" message={error} />;
      if (!powerData?.length) return <TRDefault type="lock" />;
    }
    return (
      <Spin spinning={dataLoading} wrapperClassName={styles.spin}>
        <div className={styles.tool} style={{ top: !result ? 0 : 70 }}>
          <Tool
            buttonPermissions={buttonPermissions}
            defaultForm={form}
            pageType={pageType}
            powerData={powerData}
            onAction={onAction}
            onChangeForm={(upValues) =>
              setForm({
                ...form,
                ...upValues,
              })
            }
          />
        </div>
        {_renderMain()}
      </Spin>
    );
  };

  return (
    <div className={styles.page} ref={wrapRef}>
      {_render()}
    </div>
  );
}
